const express = require('express')
const api = express.Router()
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017/adv'
const uuid = require('node-uuid')  // 生成uuid
const userSchema = require('../model/userSchema')
const advListSchema = require('../model/advListSchema')


MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
  if (err) throw err
  const dbo = db.db('adv')

  // 验证登录信息
  api.post('/login', function(req, res, next) {
    userSchema.findOne({"userName": req.body.userName,}, function(err, result) {  
      if(result === null){
        res.send({
          success: false,
          msg: '用户名不正确'
        })
      }else{
        if(req.body.userPwd === result.userPwd){
          res.send({success: true})
        }else{
          res.send({
            success: false,
            msg: '密码不正确'
          })
        }       
      }      
    })
  })

  // 修改advList单条数据,通过 id 获取数据  
  api.post('/getEditAdv', function(req, res, next) {
    let str = {"id": req.body.id} 
    advListSchema.findOne(str, function(err, result) {
      if(err) throw err      
      res.send(result)
    })       
  })

  // 保存广告信息
  api.post('/saveAdv', function(req, res, next) {
    let id = req.body.id    
    if(id){   // 有id时进行更新操作
      let updateData = {
        "advName": req.body.advName,
        "advPosition": req.body.advPosition,
        "advType": req.body.advType
      }
      advListSchema.updateOne({"id": id}, {$set: updateData}, function(err, result) {
        if(err) throw err
        res.send({success: true})
        console.log('[saveAdv]：数据更新成功')
      })
    }else{   // 没有id时进行插入操作
      let insertData = {
        "id": uuid.v1(),
        "advName": req.body.advName,
        "advPosition": req.body.advPosition,
        "advType": req.body.advType
      }
      advListSchema.create(insertData, function(err, result) {
        if(err) throw err
        res.send({
          success: true,
          msg: '保存成功'
        })
        console.log('[saveAdv]：数据插入成功')
      })
    }    
  })

  // 删除单条广告
  api.post('/delAdv', function(req, res, next) {
    let str = {id: req.body.id}
    advListSchema.remove(str, function(err, result) {
      if(err) throw err
      res.send({
        success: true,
        msg: '删除成功'
      })
      console.log('[delAdv]：删除成功')
    })
  })
  

})

module.exports = api
